package com.pubg.servlet;

import com.pubg.service.ProductService;
import com.pubg.service.ProductTypeService;
import com.pubg.service.impl.ProductServiceImpl;
import com.pubg.service.impl.ProductTypeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "IndexServlet",urlPatterns = "/main")
public class IndexServlet extends HttpServlet {
    private ProductService productService = new ProductServiceImpl();
    private ProductTypeService productTypeService = new ProductTypeServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String opr = request.getParameter("opr");
        if (opr.equals("typeList")){
            doTypeList(request,response,out);
        }else if (opr.equals("productList")){
            doList(request,response,out);
        }
    }

    /**
     * 商品信息
     * @param request
     * @param response
     * @param out
     */
    private void doList(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws ServletException, IOException {
        request.setAttribute("productList",productService.list());
        System.out.println(productService.list().size());
        request.getRequestDispatcher("index.jsp").forward(request,response);
    }

    /**
     * 商品分类
     * @param request
     * @param response
     * @param out
     * @throws ServletException
     * @throws IOException
     */
    private void doTypeList(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws ServletException, IOException {
        request.getSession().setAttribute("typeList",productTypeService.getList());
        request.getRequestDispatcher("index.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
